package com.rising.threads.volatiles;

/**
 * @Author: rising
 * @Description:
 * @Date: create in 2020/11/8 14:12
 */

/**
 * 验证Volatile可见性
 */
public class VolatileDemo {
    public static void main(String[] args) {
        //Mydata mydata = new Mydata();

        /*new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "\t come in");
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            mydata.addTo60();
            System.out.println(Thread.currentThread().getName() + "\t update number value:" + mydata.number);
        }, "AAA").start();*/
        /*for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                for (int j = 0; j < 100; j++) {
                    mydata.addPlusPlus();
                }
            }, i + "").start();
        }

        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(mydata.number);
        System.out.println(Thread.currentThread().getName() + "\t mission is over");*/

        Mydata2 mydata2 = new Mydata2();
        new Thread(() -> {
            mydata2.method1();
        }, "method1").start();

        new Thread(() -> {
            mydata2.method2();
        }, "------method2").start();
    }
}

class Mydata {
    int number = 0;
    public void addTo60() {
        number = number + 60;
    }

    public synchronized void addPlusPlus() {
        number++;
    }
}

class Mydata2 {

     boolean flag = true;

    public void method1() {
        try {
            //TimeUnit.MILLISECONDS.sleep(500);
            System.out.println(Thread.currentThread().getName() + ", number = " + flag);
            flag = false;
            //TimeUnit.SECONDS.sleep(1);
            System.out.println(Thread.currentThread().getName() + ", number = " + flag);
            flag = false;
            //TimeUnit.SECONDS.sleep(1);
            System.out.println(Thread.currentThread().getName() + ", number = " + flag);
            flag = false;
            //TimeUnit.SECONDS.sleep(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void method2() {
        try {

            System.out.println(Thread.currentThread().getName() + ", number = " + flag);
            //TimeUnit.SECONDS.sleep(1);
            System.out.println(Thread.currentThread().getName() + ", number = " + flag);
            //TimeUnit.SECONDS.sleep(1);
            System.out.println(Thread.currentThread().getName() + ", number = " + flag);
            //TimeUnit.SECONDS.sleep(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

